#pragma once
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define DEV "/dev/null"

void daemonSelf(const char* currpath = nullptr)
{
    //1.屏蔽信号
    signal(SIGPIPE,SIG_IGN); 

    //2.自成进程组
    if(fork() > 0 ) exit(0); //父进程秒退
    //子进程自成进程组
    pid_t ret = setsid(); 
    assert(ret != -1); 

    //3.关闭默认打开的文件
    int fd = open(DEV,O_RDWR); 
    if(fd < 0)
    {
        //文件打开失败，那么就关闭标准输入/输出/错误
        close(0);
        close(1);
        close(2);
    }else{
        //替换掉标准输入输出错误
        dup2(fd,0);
        dup2(fd,1);
        dup2(fd,2);
    }

    //4. 路径修改
    if(currpath) chdir(currpath);
    close(fd);
}